const hasher = require('pbkdf2-password')()
const express = require('express')
const login = express.Router()
const { Password } = require('../../model/password')
const { User } = require('../../model/user')

module.exports =  async (req,res) => {
        const {email,password} = req.body

        if(email.trim().length == 0 || password.trim().length == 0) {
            res.render('admin/login',{
                showFlag:1,
                data:'账号或密码不能为空'
            })
        }   
        let result = await User.findOne({email}).populate('password')
        if(result){
            hasher({password,salt:result.password.salt},(err, pass, salt, hash)=>{
                if(err) throw err
                if(hash == result.password.hash){
                    req.session.username = result.username
                    req.session.role = result.role
                    req.app.locals.userInfo = result
                    res.redirect('/admin/user')

                }else{
                    // res.sendResult(null,400,'账户或密码错误')
                    res.render('admin/login',{
                        showFlag:1,
                        data:'账户或密码错误'
                    })
                }
            })
        }
        else {
            // res.sendResult(null,400,'账户或密码错误')
            res.render('admin/login',{
                showFlag:1,
                data:'账户或密码错误'
            })
        }
    }

